C Shell
   HOME

TheInfoList



OR:

The C shell (csh or the improved version,
tcsh tcsh ( “tee-see-shell”, “tee-shell”, or as “tee see ess aitch”, tcsh) is a Unix shell based on and backward compatible with the C shell (csh). Shell It is essentially the C shell with programmable command-line completion, command-l ...
) is a
Unix shell A Unix shell is a command-line Interpreter (computing), interpreter or shell (computing), shell that provides a command line user interface for Unix-like operating systems. The shell is both an interactive command language and a scripting langua ...
created by
Bill Joy William Nelson Joy (born November 8, 1954) is an American computer engineer and venture capitalist. He co-founded Sun Microsystems in 1982 along with Scott McNealy, Vinod Khosla, and Andy Bechtolsheim, and served as Chief Scientist and CTO at ...
while he was a graduate student at
University of California, Berkeley The University of California, Berkeley (UC Berkeley, Berkeley, Cal, or California) is a public land-grant research university in Berkeley, California. Established in 1868 as the University of California, it is the state's first land-grant u ...
in the late 1970s. It has been widely distributed, beginning with the 2BSD release of the Berkeley Software Distribution (BSD) which Joy first distributed in 1978. Other early contributors to the ideas or the code were Michael Ubell,
Eric Allman Eric Paul Allman (born September 2, 1955) is an American computer programmer who developed sendmail and its precursor delivermail in the late 1970s and early 1980s at UC Berkeley. In 1998, Allman and Greg Olson co-founded the company Sendmail, I ...
, Mike O'Brien and Jim Kulp. The C shell is a
command processor A command-line interpreter or command-line processor uses a command-line interface (CLI) to receive commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invoking executables and pro ...
which is typically run in a text window, allowing the user to type and execute commands. The C shell can also read commands from a file, called a
script Script may refer to: Writing systems * Script, a distinctive writing system, based on a repertoire of specific elements or symbols, or that repertoire * Script (styles of handwriting) ** Script typeface, a typeface with characteristics of handw ...
. Like all Unix shells, it supports filename wildcarding,
piping Within industry, piping is a system of pipes used to convey fluids (liquids and gases) from one location to another. The engineering discipline of piping design studies the efficient transport of fluid. Industrial process piping (and accompan ...
,
here document In computing, a here document (here-document, here-text, heredoc, hereis, here-string or here-script) is a file literal or input stream literal: it is a section of a source code file that is treated as if it were a separate file. The term is also ...
s,
command substitution In computing, command substitution is a facility that allows a command to be run and its output to be pasted back on the command line as arguments to another command. Command substitution first appeared in the Bourne shell, introduced with Version ...
, variables and
control structures In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''imp ...
for condition-testing and
iteration Iteration is the repetition of a process in order to generate a (possibly unbounded) sequence of outcomes. Each repetition of the process is a single iteration, and the outcome of each iteration is then the starting point of the next iteration. ...
. What differentiated the C shell from others, especially in the 1980s, were its interactive features and overall style. Its new features made it easier and faster to use. The overall style of the language looked more like C and was seen as more readable. On many systems, such as
macOS macOS (; previously OS X and originally Mac OS X) is a Unix operating system developed and marketed by Apple Inc. since 2001. It is the primary operating system for Apple's Mac computers. Within the market of desktop and lapt ...
and
Red Hat Linux Red Hat Linux was a widely used commercial open-source Linux distribution created by Red Hat until its discontinuation in 2004. Early releases of Red Hat Linux were called Red Hat Commercial Linux. Red Hat published the first non-beta rele ...
, csh is actually
tcsh tcsh ( “tee-see-shell”, “tee-shell”, or as “tee see ess aitch”, tcsh) is a Unix shell based on and backward compatible with the C shell (csh). Shell It is essentially the C shell with programmable command-line completion, command-l ...
, an improved version of csh. Often one of the two files is either a hard link or a
symbolic link In computing, a symbolic link (also symlink or soft link) is a file whose purpose is to point to a file or directory (called the "target") by specifying a path thereto. Symbolic links are supported by POSIX and by most Unix-like operating syste ...
to the other, so that either name refers to the same improved version of the C shell. The original csh source code and binary are part of NetBSD. On Debian and some derivatives (including
Ubuntu Ubuntu ( ) is a Linux distribution based on Debian and composed mostly of free and open-source software. Ubuntu is officially released in three editions: '' Desktop'', ''Server'', and ''Core'' for Internet of things devices and robots. All ...
), there are two different packages: csh and tcsh. The former is based on the original BSD version of csh and the latter is the improved tcsh. tcsh added filename and command completion and command line editing concepts borrowed from the Tenex system, which is the source of the "t". Because it only added functionality and did not change what already existed, tcsh remained
backward compatible Backward compatibility (sometimes known as backwards compatibility) is a property of an operating system, product, or technology that allows for interoperability with an older legacy system, or with input designed for such a system, especially in ...
with the original C shell. Though it started as a side branch from the original source tree Joy had created, tcsh is now the main branch for ongoing development. tcsh is very stable but new releases continue to appear roughly once a year, consisting mostly of minor bug fixes.


Design objectives and features

The main design objectives for the C shell were that it should look more like the
C programming language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the language, as well as ...
and that it should be better for interactive use.


More like C

The Unix system had been written almost exclusively in C, so the C shell's first objective was a command language that was more stylistically consistent with the rest of the system. The keywords, the use of parentheses, and the C shell's built-in expression grammar and support for arrays were all strongly influenced by C. By today's standards, C shell may not seem particularly more C-like than many other popular scripting languages. But through the 80s and 90s, the difference was seen as striking, particularly when compared to Bourne shell (also known as ''sh''), the then-dominant shell written by Stephen Bourne at
Bell Labs Nokia Bell Labs, originally named Bell Telephone Laboratories (1925–1984), then AT&T Bell Laboratories (1984–1996) and Bell Labs Innovations (1996–2007), is an American industrial research and scientific development company owned by mult ...
. This example illustrates the C shell's more conventional expression operators and
syntax In linguistics, syntax () is the study of how words and morphemes combine to form larger units such as phrases and sentences. Central concerns of syntax include word order, grammatical relations, hierarchical sentence structure ( constituency) ...
. The Bourne sh lacked an expression grammar. The square bracketed condition had to be evaluated by the slower means of running the external
test Test(s), testing, or TEST may refer to: * Test (assessment), an educational assessment intended to measure the respondents' knowledge or other abilities Arts and entertainment * ''Test'' (2013 film), an American film * ''Test'' (2014 film), ...
program. sh's if command took its argument words as a new command to be run as a
child process A child process in computing is a process created by another process (the parent process). This technique pertains to multitasking operating systems, and is sometimes called a subprocess or traditionally a subtask. There are two major procedure ...
. If the child exited with a zero
return code In computer programming, a return code or an error code is a numeric or alphanumeric code that is used to determine the nature of an error and why it occurred. They are also commonly found in consumer electronics and devices when they attempt to ...
, sh would look for a then clause (a separate statement, but often written joined on the same line with a semicolon) and run that nested block. Otherwise, it would run the else. Hard-linking the test program as both "test" and "[" gave the notational advantage of the square brackets and the appearance that the functionality of test was part of the sh language. sh's use of a reversed keyword to mark the end of a control block was a style borrowed from ALGOL 68. By contrast, csh could evaluate the expression directly, which made it faster. It also claimed better readability: Its expressions used a
grammar In linguistics, the grammar of a natural language is its set of structure, structural constraints on speakers' or writers' composition of clause (linguistics), clauses, phrases, and words. The term can also refer to the study of such constraint ...
and a set of operators mostly copied from C, none of its keywords were reversed and the overall style was also more like C. Here is a second example, comparing scripts that calculate the first 10 powers of 2. Again because of the lack of an expression grammar, the sh script uses
command substitution In computing, command substitution is a facility that allows a command to be run and its output to be pasted back on the command line as arguments to another command. Command substitution first appeared in the Bourne shell, introduced with Version ...
and the expr command. (Modern
POSIX shell A Unix shell is a command-line interpreter or shell that provides a command line user interface for Unix-like operating systems. The shell is both an interactive command language and a scripting language, and is used by the operating system to ...
''does'' have such a grammar: the statement could be written or .) Finally, here is a third example, showing the differing styles for a switch statement. In the sh script, ";;" marks the end of each case because sh disallows null statements otherwise.


Improvements for interactive use

The second objective was that the C shell should be better for interactive use. It introduced numerous new features that made it easier, faster and more friendly to use by typing commands at a terminal. Users could get things done with a lot fewer keystrokes and it ran faster. The most significant of these new features were the history and editing mechanisms, aliases, directory stacks, tilde notation, cdpath, job control, and path hashing. These new features proved very popular, and many of them have since been copied by other Unix shells.


History

History allows users to recall previous commands and rerun them by typing only a few quick keystrokes. For example, typing two exclamation marks ("!!") as a command causes the immediately preceding command to be run. Other short keystroke combinations, e.g., "!$" (meaning "the final argument of the previous command"), allow bits and pieces of previous commands to be pasted together and edited to form a new command.


Editing operators

Editing can be done not only on the text of a previous command, but also on variable substitutions. Operators range from simple string search/replace to parsing a pathname to extract a specific segment.


Aliases

Aliases allow the user to type the name of an alias and have the C shell expand it internally into whatever set of words the user has defined. For many simple situations, aliases run faster and are more convenient than scripts.


Directory stack

The directory stack allows the user to push or pop the
current working directory In computing, the working directory of a process is a directory of a hierarchical file system, if any, dynamically associated with each process. It is sometimes called the current working directory (CWD), e.g. the BSD getcwd function, or just ...
, making it easier to jump back and forth between different places in the filesystem.


Tilde notation

Tilde notation offers a shorthand way of specifying pathnames relative to the home directory using the "~" character.


Filename completion

The
escape key On computer keyboards, the Esc key (named ''Escape key'' in the international standard series ISO/IEC 9995) is a key used to generate the escape character (which can be represented as ASCII code 27 in decimal, Unicode U+001B, or ). The escape ...
can be used interactively to show possible completions of a filename at the end of the current command line.


Cdpath

Cdpath extends the notion of a search path to the cd (change directory) command: If the specified directory is not in the
current directory In computing, the working directory of a process is a directory of a hierarchical file system, if any, dynamically associated with each process. It is sometimes called the current working directory (CWD), e.g. the BSD getcwd function, or just cu ...
, csh will try to find it in the cdpath directories.


Job control

Well into the 1980s, most users only had simple character-mode terminals that precluded multiple windows, so they could only work on one task at a time. The C shell's job control allowed the user to suspend the current activity and create a new instance of the C shell, called a job, by typing ^Z. The user could then switch back and forth between jobs using the fg command. The active job was said to be in the foreground. Other jobs were said to be either suspended (stopped) or running in the
background Background may refer to: Performing arts and stagecraft * Background actor * Background artist * Background light * Background music * Background story * Background vocals * ''Background'' (play), a 1950 play by Warren Chetham-Strode Record ...
.


Path hashing

Path hashing speeds up the C shell's search for executable files. Rather than performing a filesystem call in each path directory, one at a time, until it either finds the file or runs out of possibilities, the C shell consults an internal
hash table In computing, a hash table, also known as hash map, is a data structure that implements an associative array or dictionary. It is an abstract data type that maps keys to values. A hash table uses a hash function to compute an ''index'', als ...
built by scanning the path directories. That table can usually tell the C shell where to find the file (if it exists) without having to search and can be refreshed with the rehash command.


Overview of the language

The C shell operates one line at a time. Each line is
tokenized In computer science, lexical analysis, lexing or tokenization is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of ''lexical tokens'' ( strings with an assigned and thus identified ...
into a set of words separated by spaces or other characters with special meaning, including parentheses, piping and input/output redirection operators, semicolons, and ampersands.


Basic statements

A basic statement is one that simply runs a command. The first word is taken as name of the command to be run and may be either an internal command, e.g., echo, or an external command. The rest of the words are passed as arguments to the command. At the basic statement level, here are some of the features of the grammar:


Wildcarding

The C shell, like all Unix shells, treats any command-line argument that contains wildcard characters as a pattern and replaces it with the list of all the filenames that match (see
globbing In computer programming, glob () patterns specify sets of filenames with wildcard characters. For example, the Unix Bash shell command mv *.txt textfiles/ moves (mv) all files with names ending in .txt from the current directory to the director ...
). ** matches any number of characters. *? matches any single character. * /code>.../code> matches any of the characters inside the square brackets. Ranges are allowed, using the hyphen. * .../code> matches any character ''not'' in the set. The C shell also introduced several notational conveniences (sometimes known as extended globbing), since copied by other Unix shells. *abc is alternation (aka
brace expansion Bash is a Unix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell. First released in 1989, it has been used as the default login shell for most Linux distributions. Bash was o ...
) and expands to ''abcdef'' ''abcghi''. *~ means the current user's home directory. *~user means ''users home directory. Multiple directory-level wildcards, e.g., "*/*.c", are supported. Since version 6.17.01, recursive wildcarding à la
zsh The Z shell (Zsh) is a Unix shell that can be used as an interactive login shell (computing), shell and as a command line interpreter, command interpreter for shell scripting. Zsh is an extended Bourne shell with many improvements, including som ...
(e.g. "**/*.c" or "***/*.html") is also supported with the globstar option. Giving the shell the responsibility for interpreting wildcards was an important decision on Unix. It meant that wildcards would work with every command, and always in the same way. However, the decision relied on Unix's ability to pass long argument lists efficiently through the
exec Exec or EXEC may refer to: * Executive officer, a person responsible for running an organization * Executive producer, provides finance and guidance for the making of a commercial entertainment product * A family of kit helicopters produced by Rot ...
system call that csh uses to execute commands. By contrast, on
Windows Windows is a group of several proprietary graphical operating system families developed and marketed by Microsoft. Each family caters to a certain sector of the computing industry. For example, Windows NT for consumers, Windows Server for serv ...
, wildcard interpretation is conventionally performed by each application. This is a legacy of MS-DOS, which only allowed a 128-byte command line to be passed to an application, making wildcarding by the DOS command prompt impractical. Although modern
Windows Windows is a group of several proprietary graphical operating system families developed and marketed by Microsoft. Each family caters to a certain sector of the computing industry. For example, Windows NT for consumers, Windows Server for serv ...
can pass command lines of up to roughly 32K
Unicode Unicode, formally The Unicode Standard,The formal version reference is is an information technology Technical standard, standard for the consistent character encoding, encoding, representation, and handling of Character (computing), text expre ...
characters, the burden for wildcard interpretation remains with the application.


I/O redirection

By default, when csh runs a command, the command inherits the csh's stdio file handles for
stdin In computer programming, standard streams are interconnected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin ...
,
stdout In computer programming, standard streams are interconnected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin ...
and stderr, which normally all point to the console window where the C shell is running. The i/o redirection operators allow the command to use a file instead for input or output. *> ''file'' means stdout will be written to ''file'', overwriting it if it exists, and creating it if it doesn't. Errors still come to the shell window. *>& ''file'' means both stdout and stderr will be written to ''file'', overwriting it if it exists, and creating it if it doesn't. *>> ''file'' means stdout will be appended at the end of ''file''. *>>& ''file'' means both stdout and stderr will be appended at the end of ''file''. *< ''file'' means stdin will be read from ''file''. *<< ''string'' is a
here document In computing, a here document (here-document, here-text, heredoc, hereis, here-string or here-script) is a file literal or input stream literal: it is a section of a source code file that is treated as if it were a separate file. The term is also ...
. Stdin will read the following lines up to the one that matches ''string''. Redirecting stderr alone isn't possible without the aid of a sub-shell. mkfifo ~/filter setenv filter "~/filter" cat $filter & ( ( ls /root/ , , echo No access. ) > $filter ) >& /dev/null


Joining

Commands can be joined on the same line. *; means run the first command and then the next. *&& means run the first command and, if it succeeds with a 0
return code In computer programming, a return code or an error code is a numeric or alphanumeric code that is used to determine the nature of an error and why it occurred. They are also commonly found in consumer electronics and devices when they attempt to ...
, run the next. *, , means run the first command and, if it fails with a non-zero return code, run the next.


Piping

Commands can be connected using a pipe, which causes the output of one command to be fed into the input of the next. Both commands run concurrently. *, means connect stdout to stdin of the next command. Errors still come to the shell window. *, & means connect both stdout and stderr to stdin of the next command. Running concurrently means "in parallel". In a multi-core (multiple processor) system, the piped commands may literally be executing at the same time, otherwise the
scheduler A schedule or a timetable, as a basic time-management tool, consists of a list of times at which possible tasks, events, or actions are intended to take place, or of a sequence of events in the chronological order in which such things are i ...
in the operating system time-slices between them. Given a command, e.g., "a , b", the shell creates a
pipe Pipe(s), PIPE(S) or piping may refer to: Objects * Pipe (fluid conveyance), a hollow cylinder following certain dimension rules ** Piping, the use of pipes in industry * Smoking pipe ** Tobacco pipe * Half-pipe and quarter pipe, semi-circular ...
, then starts both a and b with stdio for the two commands redirected so that a writes its stdout into the input of the pipe while b reads stdin from the output of the pipe. Pipes are implemented by the operating system with a certain amount of buffering so that a can write for a while before the pipe fills but once the pipe fills any new write will block inside the OS until b reads enough to unblock new writes. If b tries to read more data than is available, it will block until a has written more data or until the pipe closes, e.g., if a exits.


Variable substitution

If a word contains a dollar sign, "$", the following characters are taken as the name of a variable and the reference is replaced by the value of that variable. Various editing operators, typed as suffixes to the reference, allow pathname editing (e.g., ":e" to extract just the extension) and other operations.


Quoting and escaping

Quoting mechanisms allow otherwise special characters, such as whitespace, wildcards, parentheses, and dollar signs, to be taken as literal text. *\ means take the next character as an ordinary literal character. *"''string''" is a weak quote. Enclosed whitespace and wildcards are taken as literals, but variable and command substitutions are still performed. *'''string''' is a strong quote. The entire enclosed string is taken as a literal. Double quotes inside double quotes should be escaped with "\"". The same applies to the dollar symbol, to prevent variable expansion "\$". For backticks, to prevent command substitution nesting, single quotes are required "'\`'".


Command substitution

Command substitution allows the output of one command to be used as arguments to another. *`''command''` means take the output of ''command'', parse it into words and paste them back into the command line. The following is an example of nested command substitutions. echo "`echo "\"'`echo "\"'\''`echo "\"'\'\\\'\''`echo "\"'\'\\\'\\\\\\\'\\\'\''`echo "\"'\'\\\'\\\\\\\'\\\\\\\\\\\\\\\'\\\\\\\'\\\'\''`echo "\"'\'\\\'\\\\\\\'\\\\\\\\\\\\\\\'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'\\\\\\\\\\\\\\\'\\\\\\\'\\\'\''`echo "\`"pwd"\`"`'\'\\\'\\\\\\\'\\\\\\\\\\\\\\\'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'\\\\\\\\\\\\\\\'\\\\\\\'\\\'\''\""`'\'\\\'\\\\\\\'\\\\\\\\\\\\\\\'\\\\\\\'\\\'\''\""`'\'\\\'\\\\\\\'\\\'\''\""`'\'\\\'\''\""`'\''\""`'\""`"


Background execution

Normally, when the C shell starts a command, it waits for the command to finish before giving the user another prompt signaling that a new command can be typed. *''command'' & means start ''command'' in the background and prompt immediately for a new command.


Subshells

A subshell is a separate child copy of the shell that inherits the current state but can then make changes, e.g., to the current directory, without affecting the parent. *( ''commands'' ) means run ''commands'' in a subshell.


Control structures

The C shell provides control structures for both condition-testing and
iteration Iteration is the repetition of a process in order to generate a (possibly unbounded) sequence of outcomes. Each repetition of the process is a single iteration, and the outcome of each iteration is then the starting point of the next iteration. ...
. The condition-testing control structures are the if and switch statements. The iteration control structures are the while, foreach and repeat statements.


if statement

There are two forms of the
if statement In computer science, conditionals (that is, conditional statements, conditional expressions and conditional constructs,) are programming language commands for handling decisions. Specifically, conditionals perform different computations or actio ...
. The short form is typed on a single line but can specify only a single command if the expression is true. if ( expression ) command The long form uses then, else and endif keywords to allow for blocks of commands to be nested inside the condition. if ( expression1 ) then commands else if ( expression2 ) then commands ... else commands endif If the else and if keywords appear on the same line, csh chains, rather than nests them; the block is terminated with a single endif.


switch statement

The switch statement compares a string against a list of patterns, which may contain wildcard characters. If nothing matches, the default action, if there is one, is taken. switch ( string ) case pattern1: commands breaksw case pattern2: commands breaksw ... default: commands breaksw endsw


while statement

The while statement evaluates an expression. If it is true, the shell runs the nested commands and then repeats for as long as the expression remains true. while ( expression ) commands end


foreach statement

The foreach statement takes a list of values, usually a list of filenames produced by wildcarding, and then for each, sets the loop variable to that value and runs the nested commands. foreach loop-variable ( list-of-values ) commands end


repeat statement

The repeat statement repeats a single command an integral number of times. repeat integer command


Variables

The C shell implements both shell and
environment variable An environment variable is a dynamic-named value that can affect the way running processes will behave on a computer. They are part of the environment in which a process runs. For example, a running process can query the value of the TEMP envi ...
s. Environment variables, created using the setenv statement, are always simple strings, passed to any child processes, which retrieve these variables via the envp /a>/code> argument to main(). Shell variables, created using the set or @ statements, are internal to C shell. They are not passed to child processes. Shell variables can be either simple strings or arrays of strings. Some of the shell variables are predefined and used to control various internal C shell options, e.g., what should happen if a wildcard fails to match anything. In current versions of csh, strings can be of arbitrary length, well into millions of characters.


Expressions

The C shell implements a 32-bit integer expression grammar with operators borrowed from C but with a few additional operators for string comparisons and filesystem tests, e.g., testing for the existence of a file. Operators must be separated by whitespace from their operands. Variables are referenced as $''name''.
Operator precedence In mathematics and computer programming, the order of operations (or operator precedence) is a collection of rules that reflect conventions about which procedures to perform first in order to evaluate a given mathematical expression. For exampl ...
is also borrowed from C, but with different
operator associativity In programming language theory, the associativity of an operator is a property that determines how operators of the same precedence are grouped in the absence of parentheses. If an operand is both preceded and followed by operators (for example ...
rules to resolve the ambiguity of what comes first in a sequence of equal precedence operators. In C, the associativity is left-to-right for most operators; in C shell, it is right-to-left. For example, The parentheses in the C shell example are to avoid having the bit-shifting operators confused as I/O redirection operators. In either language, parentheses can always be used to explicitly specify the desired order of evaluation, even if only for clarity.


Reception

Although Stephen Bourne himself acknowledged that csh was superior to his shell for interactive use, it has never been as popular for scripting. Initially, and through the 1980s, csh could not be guaranteed to be present on all Unix systems, but sh could, which made it a better choice for any scripts that might have to run on other machines. By the mid-1990s, csh was widely available, but the use of csh for scripting faced new criticism by the
POSIX The Portable Operating System Interface (POSIX) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines both the system- and user-level application programming inter ...
committee, which specified that there should only be one preferred shell, the KornShell, for both interactive and scripting purposes. The C shell also faced criticism from others over the C shell's alleged defects in syntax, missing features, and poor implementation. *Syntax defects: were generally simple but unnecessary inconsistencies in the definition of the language. For example, the set, setenv and alias commands all did basically the same thing, namely, associate a name with a string or set of words. But all three had slight but unnecessary differences. An equal sign was required for a set but not for setenv or alias; parentheses were required around a word list for a set but not for setenv or alias, etc. Similarly, the if, switch and looping constructs use needlessly different keywords (endif, endsw and end) to terminate the nested blocks. *Missing features: most commonly cited are the lack of ability to manipulate the
stdio The C programming language provides many standard library functions for file input and output. These functions make up the bulk of the C standard library header . The functionality descends from a "portable I/O package" written by Mike Lesk at ...
file handles independently and support for functions. Although lacking support for functions, aliases serve as workaround. For multiple lines of code, aliases must be within single quotes, and each end of line must precede a backslash (the end of the last line must precede a single quote to delimit the end of the alias). *The implementation: which used an ad hoc
parser Parsing, syntax analysis, or syntactic analysis is the process of analyzing a string of symbols, either in natural language, computer languages or data structures, conforming to the rules of a formal grammar. The term ''parsing'' comes from Lat ...
, has drawn the most serious criticism. By the early 1970s,
compiler In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
technology was sufficiently mature that most new language implementations used either a
top-down Top-down may refer to: Arts and entertainment * " Top Down", a 2007 song by Swizz Beatz * "Top Down", a song by Lil Yachty from ''Lil Boat 3'' * "Top Down", a song by Fifth Harmony from ''Reflection'' Science * Top-down reading, is a part of ...
or
bottom-up parser Bottom-up may refer to: * Bottom-up analysis, a fundamental analysis technique in accounting and finance * Bottom-up parsing, a computer science strategy * Bottom-up processing, in Pattern recognition (psychology) * Bottom-up theories of galaxy fo ...
capable of recognizing a fully recursive
grammar In linguistics, the grammar of a natural language is its set of structure, structural constraints on speakers' or writers' composition of clause (linguistics), clauses, phrases, and words. The term can also refer to the study of such constraint ...
. It is not known why an ad hoc design was chosen instead for the C shell. It may be simply that, as Joy put it in an interview in 2009, "When I started doing this stuff with Unix, I wasn’t a very good programmer." The ad hoc design meant that the C shell language was not fully recursive. There was a limit to how complex a command it could handle. It worked for most interactively typed commands, but for the more complex commands a user might write in a script, it could easily fail, producing only a cryptic error message or an unwelcome result. For example, the C shell could not support piping between control structures. Attempting to pipe the output of a foreach command into
grep grep is a command-line utility for searching plain-text data sets for lines that match a regular expression. Its name comes from the ed command ''g/re/p'' (''globally search for a regular expression and print matching lines''), which has the sa ...
simply didn't work. (The work-around, which works for many of the complaints related to the parser, is to break the code up into separate scripts. If the foreach is moved to a separate script, piping works because scripts are run by forking a new copy of csh that does inherit the correct stdio handles.) Another example is the unwelcome behavior in the following fragments. Both of these appear to mean, "If 'myfile' does not exist, create it by writing 'mytext' into it." But the version on the right always creates an empty file because the C shell's order of evaluation is to look for and evaluate I/O redirection operators on each command line as it reads it, before examining the rest of the line to see whether it contains a control structure. The implementation is also criticized for its notoriously poor error messages, e.g., "0: Event not found.", which yields no useful information about the problem. However, by practicing, it's possible to overcome those deficiencies (thus instructing the programmer to take better and safer approaches on implementing a script). # Second workaround (for csh and tcsh) ( ( : < myfile ) >& /dev/null && echo File exists. ) , , ( ( echo mytext > myfile ) >& /dev/null && echo File created. ) , , ( echo Cannot create file. ) The "0: Event not found." error implies there aren't saved commands in the history. The history may not work properly in scripts, but having a pre-set of commands in a variable serves as workaround. #!/bin/csh -f set cmdlist = "`cat .cmdlist`" echo -n 'Enter a number to execute a command from the history: ' set cmdexec = "$<" ( echo $cmdexec , grep -qa ' 0-9 && \ echo 'Must be a number.' ) && exit 1 `echo $cmdlist cmdexec , , \ cat -n .cmdlist


Influence

The C shell was extremely successful in introducing a large number of innovations including the
history History (derived ) is the systematic study and the documentation of the human activity. The time period of event before the History of writing#Inventions of writing, invention of writing systems is considered prehistory. "History" is an umbr ...
mechanism,
aliases A pseudonym (; ) or alias () is a fictitious name that a person or group assumes for a particular purpose, which differs from their original or true name ( orthonym). This also differs from a new name that entirely or legally replaces an individu ...
, tilde notation, interactive filename completion, an expression grammar built into the shell, and more, that have since been copied by other Unix shells. But in contrast to sh, which has spawned a large number of independently developed clones, including ksh and
bash Bash or BASH may refer to: Arts and entertainment * ''Bash!'' (Rockapella album), 1992 * ''Bash!'' (Dave Bailey album), 1961 * '' Bash: Latter-Day Plays'', a dramatic triptych * ''BASH!'' (role-playing game), a 2005 superhero game * "Bash" ('' ...
, only two csh
clones Clone or Clones or Cloning or Cloned or The Clone may refer to: Places * Clones, County Fermanagh * Clones, County Monaghan, a town in Ireland Biology * Clone (B-cell), a lymphocyte clone, the massive presence of which may indicate a pathologi ...
are known. (Since
tcsh tcsh ( “tee-see-shell”, “tee-shell”, or as “tee see ess aitch”, tcsh) is a Unix shell based on and backward compatible with the C shell (csh). Shell It is essentially the C shell with programmable command-line completion, command-l ...
was based on the csh code originally written by Bill Joy, it is not considered a clone.) In 1986,
Allen Holub Allen, Allen's or Allens may refer to: Buildings * Allen Arena, an indoor arena at Lipscomb University in Nashville, Tennessee * Allen Center, a skyscraper complex in downtown Houston, Texas * Allen Fieldhouse, an indoor sports arena on the Univer ...
wrote ''On Command: Writing a Unix-Like Shell for
MS-DOS MS-DOS ( ; acronym for Microsoft Disk Operating System, also known as Microsoft DOS) is an operating system for x86-based personal computers mostly developed by Microsoft. Collectively, MS-DOS, its rebranding as IBM PC DOS, and a few ope ...
'', a book describing a program he had written called "SH" but which in fact copied the language design and features of csh, not sh. Companion diskettes containing full source for SH and for a basic set of Unix-like utilities (cat, cp, grep, etc.) were available for $25 and $30, respectively, from the publisher. The control structures, expression grammar, history mechanism and other features in Holub's SH were identical to those of the C shell. In 1988, Hamilton Laboratories began shipping
Hamilton C shell Hamilton C shell is a clone of the Unix C shell and utilities Early for Microsoft Windows created by Nicole Hamilton at Hamilton Laboratories as a completely original work, not based on any prior code. It was first released on OS/2 on Decem ...
for
OS/2 OS/2 (Operating System/2) is a series of computer operating systems, initially created by Microsoft and IBM under the leadership of IBM software designer Ed Iacobucci. As a result of a feud between the two companies over how to position OS/2 ...
. It included both a csh clone and a set of Unix-like utilities. In 1992, Hamilton C shell was released for
Windows NT Windows NT is a proprietary graphical operating system produced by Microsoft, the first version of which was released on July 27, 1993. It is a processor-independent, multiprocessing and multi-user operating system. The first version of Win ...
. The Windows version continues to be actively supported but the OS/2 version was discontinued in 2003. An early 1990 quick reference described the intent as "full compliance with the entire C shell language (except job control)" but with improvements to the language design and adaptation to the differences between Unix and a PC. The most important improvement was a
top-down parser Top-down parsing in computer science is a parsing strategy where one first looks at the highest level of the parse tree and works down the parse tree by using the rewriting rules of a formal grammar. LL parsers are a type of parser that uses a top-d ...
that allowed
control structure In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''imp ...
s to be nested or piped, something the original C shell could not support, given its ad hoc parser. Hamilton also added new language features including built-in and user-defined procedures, block-structured local variables and floating point arithmetic. Adaptation to a PC included support for the filename and other conventions on a PC and the use of threads instead of
forks In cutlery or kitchenware, a fork (from la, furca 'pitchfork') is a utensil, now usually made of metal, whose long handle terminates in a head that branches into several narrow and often slightly curved tines with which one can spear foods ei ...
(which were not available under either OS/2 or Windows) to achieve parallelism, e.g., in setting up a pipeline.


See also

*
Command-line interpreter A command-line interpreter or command-line processor uses a command-line interface (CLI) to receive commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invoking executables and pro ...
*
Comparison of command shells A command shell is a command-line interface to interact with and manipulate a computer's operating system. General characteristics Interactive features Background execution Background execution allows a shell to run a command without us ...


References


Further reading

* * * * *


External links


''An Introduction to the C shell''
by William Joy.
Linux in a Nutshell: Chapter 8. csh and tcsh

tcsh home page.most recent available tcsh source code.historical 2BSD csh source code
dated 2 February 1980.
The Unix Tree
complete historical Unix distributions.
Csh programming considered harmful.Top Ten Reasons not to use the C shell.
{{DEFAULTSORT:C Shell 1978 software Cross-platform free software Unix shells Software using the BSD license